//
//  UserInfoViewController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/7.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class UserInfoViewController: WarningBaseController {
    
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView(frame: CGRect.zero, style: .grouped)
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.backgroundColor = UIColor.clear
            _tableView.separatorStyle = .none
            _tableView.tableFooterView = UIView()
            _tableView.showsVerticalScrollIndicator = false
            
            _tableView.register(UserHeaderCell.self, forCellReuseIdentifier: "\(UserHeaderCell.self)")
            _tableView.register(UserCommonCell.self, forCellReuseIdentifier: "\(UserCommonCell.self)")
            
            return _tableView
        }
    }
    
    fileprivate let itemNames = [["","认证资料", "保险情况",  "更改手机号码", "修改登录密码",  "修改提现密码"], ["消息提醒", "清空缓存","我的工作轨迹"],["意见反馈", "关于太公民工"]]
    fileprivate let itemImages = [["","Icon_借款资料认证", "Icon_保险", "Icon_手机号","Icon_修改密码", "Icon_修改支付密码"], ["Icon_消息提醒", "Icon_清空缓存","gzgj"],["Icon_意见反馈","Icon_关于"]]
    fileprivate let itemBackgroundColors = [["", colorWith255RGB(255, g: 206, b: 61),colorWith255RGB(179, g: 172, b: 242),colorWith255RGB(73, g: 169, b: 238),colorWith255RGB(73, g: 169, b: 238)],[colorWith255RGB(118, g: 208, b: 163), colorWith255RGB(247, g: 153, b: 146)], [colorWith255RGB(118, g: 205, b: 211), colorWith255RGB(118, g: 205, b: 211), colorWith255RGB(126, g: 194, b: 243)]]
    
    /***本地变量***/
    fileprivate var userInfoModel: UserInfoModel? //用户信息模型
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
//        WWUser.sharedInstance.ensureCertificationStatus { (show) in
//            self.setupWarningContent(show)
//        }
  //  WWUser.sharedInstance.ensureCertificationStatus(self)
        self.checkCertificationStatus()
        self.getData()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我"
        self.view.backgroundColor = colorWith255RGB(248, g: 248, b: 248)
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.scrollableAxes
        }
        
        //self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试", style: .done, target: self, action: #selector(doRightAction))
        
        NotificationCenter.default.addObserver(self, selector: #selector(doNotificationAction), name: NSNotification.Name.init(rawValue: kNotificationUserInfoChanged), object: nil)

        self.baseView.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
         make.top.right.left.bottom.equalTo(self.baseView)
        }
    }
    
    private func checkCertificationStatus() {
        CertificationModel.checkCertificationStatus({ (response) in
            if response.success {
                WWUser.sharedInstance.ensureCertificationStatus(self)
            }
            else {
            }
        })
    }
    
    func doRightAction() {
        let vc = ViewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func doNotificationAction() {
        self.getData()
    }
    
    @objc func doLoginOutAction() {
        
        let alert  = UIAlertController(title: "确认退出吗？", message: nil, preferredStyle: .alert)
        
        let cancel = UIAlertAction(title: "取消", style: .cancel) { (action) in
            
        }
        cancel .setValue(UIColor.black, forKey: "titleTextColor")
        let choose = UIAlertAction(title: "确定", style: .default) { (action) in
            WWUser.sharedInstance.loginOut()
            let vc = LoginViewController()
            UIApplication.shared.delegate?.window!?.rootViewController = vc
            (UIApplication.shared.delegate as! AppDelegate).setTags(nil)
            RemoteNotificationModel.removeClient { (response) in
                if !response.success {
                   
                }
                else {
                   
                }
            }
            TrackUploadService.sharedInstance.stop()
        TrackUploadService.sharedInstance.stopBackGroundLocation()
        }
        alert.addAction(cancel)
        alert.addAction(choose)
        self.present(alert, animated: true) {
           
        }
    }

    fileprivate func getData() {
        UserInfoModel.getMigrantWorkInfo { (response) in
            if response.success {
                self.userInfoModel = response.value
                self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
            }
            else {
               // WWError(response.message)
            }
        }
    }

    //alert删除缓存
    fileprivate func alertDeleteCache(completion:@escaping () -> Void) {
        let alertController = UIAlertController(title:"提示", message: "删除缓存？", preferredStyle: .alert)
        
        let okAction = UIAlertAction(title: "确认", style: .default) { (action) in
            Tool.clearCache()
            completion()
        }
        
        let cancenlAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        alertController.addAction(okAction)
        alertController.addAction(cancenlAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension UserInfoViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return [6,3,2][section]
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 && indexPath.section == 0 {
            return 90 + 10
        }
        return 45
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 && indexPath.section == 0{//头像
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(UserHeaderCell.self)", for: indexPath) as! UserHeaderCell
            cell.avatarChangeHandler = {[unowned self] in
                self.getData()
            }
            
            if self.userInfoModel != nil {
                cell.bind(self.userInfoModel!)
            }else{
                cell.avatarImageView.image = UIImage.init(named: "scene_touxiang")
                let username = LoginAuthenticationService.getLastUsernameAndPassword().0
                cell.usernameLabel.text = username!+"用户"
            }
   
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(UserCommonCell.self)", for: indexPath) as! UserCommonCell
        cell.accessoryType = .disclosureIndicator
        cell.cellImageView.image = UIImage(named: itemImages[indexPath.section][indexPath.row])
        cell.itemNameLabel.text = self.itemNames[indexPath.section][indexPath.row]
        cell.itemDetailLabel.text = ""
        
        if indexPath.section == 0 {
            if indexPath.row == 3 {
                guard let model = self.userInfoModel else {
                    let username = LoginAuthenticationService.getLastUsernameAndPassword().0
                    cell.itemDetailLabel.text = Tool.securityPhoneNumber(username ?? "")
                    return cell
                }
                guard let phoneNumber = model.cellPoneNumber, phoneNumber.count == 11  else{
                    return cell
                }
                
                cell.itemDetailLabel.text = Tool.securityPhoneNumber(phoneNumber)
            }

        }
        if indexPath.section == 1 {
            if indexPath.row == 1 {
                let size = Tool.fileSizeOfCache()
                cell.itemDetailLabel.text = "\(size)" + "M"
            }
        }
        
        return cell

    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 0 {
            if indexPath.row == 1 {//认证资料
                self.checkCertificationStatus()
            WWUser.sharedInstance.ensureCertificationStatus { (status) in
                    if status == CertificationStatus.uncertified{
                        let submitVC = CertificationSubmitController.init(.certificate)
                        submitVC.hidesBottomBarWhenPushed = true
                        //submitVC.navigationItem.hidesBackButton = true
                    self.navigationController?.pushViewController(submitVC, animated: true)
                        
                    }else if status == CertificationStatus.beReturn{
                        let vc = CertificationSubmitController(.beReturn)
                        vc.hidesBottomBarWhenPushed = true
                        vc.navigationItem.hidesBackButton = false
                    self.navigationController?.pushViewController(vc, animated: true)
                    }else{
                        let vc = CertificationReviewController()
                        vc.hidesBottomBarWhenPushed = true
                    self.navigationController?.pushViewController(vc, animated: true)
                    }
                }
            }
            if indexPath.row == 2 {
                let vc = InsureInfoController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if indexPath.row == 3 {//更改手机号码
                guard self.userInfoModel != nil else {
                    return
                }
                let vc = ModifyPhoneNumberController()
                vc.hidesBottomBarWhenPushed = true
                vc.userInfoModel = self.userInfoModel
                self.navigationController?.pushViewController(vc, animated: true)
            }
            
            if indexPath.row == 4 {//修改密码
                let vc = PwdRestViewController(nibName: "PwdRestViewController", bundle: nil)
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if indexPath.row == 5 {//修改支付密码
                let vc = SetPaymentPasswordController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        if indexPath.section == 1 {
            if indexPath.row == 0 {//消息提醒
//                #if DEBUG
//                    WWInform("本功能还没有")
//                #else
//                #endif
                let vc = NotificationController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }

            
            if indexPath.row == 1 {//清空缓存
                self.alertDeleteCache(completion: { 
                    tableView.reloadRows(at: [indexPath], with: .automatic)
                })
            }
            if indexPath.row == 2{ //我的工作轨迹
                
//               let myWorkTrack = MyWorkTrackViewController(nibName: "MyWorkTrackViewController", bundle: nil)
//                myWorkTrack.hidesBottomBarWhenPushed = true;
//            self.navigationController?.pushViewController(myWorkTrack, animated: true)
            
        }
    }
        if indexPath.section == 2 {
            if indexPath.row == 0 { //意见反馈
                let vc = SuggestionController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
//            if indexPath.row == 1 {//评分
//                #if DEBUG
//                    WWInform("本功能在app上架后实现")
//                #else
//                #endif
//            }
            if indexPath.row == 1 {
                let vc = AbountViewController()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 0.1
        }
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2 {
            return 100
        }
        return 0.1
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 2 {
            let view = UIView()
            
            let loginOutButton = UIButton()
            loginOutButton.backgroundColor = colorWith255RGB(244, g: 110, b: 101)
            loginOutButton.addTarget(self, action: #selector(doLoginOutAction), for: .touchUpInside)
            loginOutButton.setTitle("退出登录", for: .normal)
            loginOutButton.titleLabel?.font = wwFont_Regular(17)
            view.addSubview(loginOutButton)
            loginOutButton.snp.makeConstraints { (make) in
                make.center.equalTo(view)
                make.left.equalTo(view).offset(20)
                make.right.equalTo(view).offset(-20)
                make.height.equalTo(50)
            }
            return view
        }
        return nil
    }
}
